import 'package:dio/dio.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:flutter_enjoy_plus/utils/http.dart';
import 'package:flutter_enjoy_plus/utils/logger.dart';
import 'package:flutter_enjoy_plus/utils/toast.dart';
import 'package:geolocator/geolocator.dart';
import 'package:permission_handler/permission_handler.dart';

class LocationList extends StatefulWidget {
  const LocationList({super.key});

  @override
  State<LocationList> createState() => _LocationListState();
}

class _LocationListState extends State<LocationList> {
  // 高德地图的key
  String key = '023080665bce23719377680ee565a651';
  String baseUrl = 'https://restapi.amap.com/v3';
  // 地址
  String address = '';
  // 周边社区列表
  List communityList = [];
  @override
  void initState() {
    getLocationPermission();
    reverseLocation(121.521763, 31.234034);
    queryNearbyCommunities(121.521763, 31.234034);
    super.initState();
  }

  // 获取权限
  Future<void> getLocationPermission() async {
    if (await Permission.location.request().isGranted) {
      ToastUtil.showSucceed('获取位置成功');
      // 获取附近位置
      getLocation();
    } else {
      ToastUtil.showError('获取位置失败');
    }
  }

  // 获取周边社区列表
  Future<void> queryNearbyCommunities(double longitude, double latitude) async {
    String url = '$baseUrl/place/around?key=$key&location=$longitude,$latitude';
    final res = await http.get(url);
    for (var item in (res['pois'] as List)) {
      setState(() {
        communityList.add(item['name']);
      });
    }
    // (res['pois'] as List).forEach((item) {
    //   setState(() {
    //     communityList.add(item['name']);
    //   });
    // });
  }

  // /geocode/regeo?location=116.310003,39.991957&key=
  // 传入经纬度获取具体位置
  Future<void> reverseLocation(double longitude, double latitude) async {
    String url =
        '$baseUrl/geocode/regeo?location=$longitude,$latitude&key=$key';
    try {
      final res = await http.get(url);
      setState(() {
        address = res['regeocode']['formatted_address'];
      });
      ToastUtil.showInfo('成功');
    } catch (e) {
      ToastUtil.showInfo('失败');
    }
  }

  Future<void> getLocation() async {
    late LocationSettings locationSettings;

    if (defaultTargetPlatform == TargetPlatform.android) {
      locationSettings = AndroidSettings(
          accuracy: LocationAccuracy.high,
          distanceFilter: 100,
          forceLocationManager: true,
          intervalDuration: const Duration(seconds: 10),
          //(Optional) Set foreground notification config to keep the app alive
          //when going to the background
          foregroundNotificationConfig: const ForegroundNotificationConfig(
            notificationText:
                "Example app will continue to receive your location even when you aren't using it",
            notificationTitle: "Running in Background",
            enableWakeLock: true,
          ));
    } else if (defaultTargetPlatform == TargetPlatform.iOS ||
        defaultTargetPlatform == TargetPlatform.macOS) {
      locationSettings = AppleSettings(
        accuracy: LocationAccuracy.high,
        activityType: ActivityType.fitness,
        distanceFilter: 100,
        pauseLocationUpdatesAutomatically: true,
        // Only set to true if our app will be started up in the background.
        showBackgroundLocationIndicator: false,
      );
    } else if (kIsWeb) {
      locationSettings = WebSettings(
        accuracy: LocationAccuracy.high,
        distanceFilter: 100,
        maximumAge: const Duration(minutes: 5),
      );
    } else {
      locationSettings = const LocationSettings(
        accuracy: LocationAccuracy.high,
        distanceFilter: 100,
      );
    }

// supply location settings to getCurrentPosition
    try {
      Position position = await Geolocator.getCurrentPosition(
          locationSettings: locationSettings);
      ToastUtil.showSucceed('经度${position.longitude}--纬度${position.latitude}');
    } catch (e) {
      ToastUtil.showError('获取失败');
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        appBar: AppBar(
          title: const Text('选择社区'),
        ),
        body: ListView(
          padding: const EdgeInsets.all(10),
          children: [
            const Row(
              children: [
                Text(
                  '当前地址',
                  style: TextStyle(color: Colors.grey),
                )
              ],
            ),
            const SizedBox(height: 10),
            Container(
              color: Colors.white,
              padding: const EdgeInsets.all(10),
              child: Row(
                children: [
                  Expanded(child: Text(address)),
                  const Row(
                    children: [
                      Icon(Icons.location_searching_outlined,
                          color: Colors.blue),
                      SizedBox(width: 2),
                      Text(
                        '重新定位',
                        style: TextStyle(color: Colors.blue),
                      ),
                    ],
                  )
                ],
              ),
            ),
            const SizedBox(height: 10),
            const Row(
              children: [
                Text(
                  '附近社区',
                  style: TextStyle(color: Colors.grey),
                )
              ],
            ),
            const SizedBox(height: 10),
            ListView(
                shrinkWrap: true,
                physics: const NeverScrollableScrollPhysics(),
                children: communityList.map((item) {
                  return GestureDetector(
                    onTap: () {
                      Navigator.pushNamed(context, '/room_list',
                          arguments: {'point': item});
                    },
                    child: Container(
                        color: Colors.white,
                        padding: const EdgeInsets.all(10),
                        child: Row(children: [
                          Expanded(child: Text(item)),
                          const Row(children: [
                            Icon(Icons.arrow_forward_ios,
                                size: 16, color: Colors.black),
                          ])
                        ])),
                  );
                }).toList())
          ],
        ));
  }
}
